package com.czk.server;

import com.czk.pojo.Invocation;
import com.czk.utils.ServerServiceCache;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/20 10:46
 */
public class MyHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("进入服务read方法了");
        System.out.println(msg.getClass());
        System.out.println(msg);
        // 校验
        if (msg instanceof Invocation) {
            System.out.println("进入nettyServer方法了");
            // 强转
            Invocation invocation = (Invocation) msg;
            // 拿到接口名称
            String interfaceName = invocation.getInterfaceName();
            // 拿到实现类
            Class clazz = ServerServiceCache.get(interfaceName);
            // 拿到方法
            String methodName = invocation.getMethodName();
            // 拿到参数类型
            Class[] paramTypes = invocation.getParamTypes();
            // 拿到参数列表
            Object[] params = invocation.getParams();
            // 执行方法
            Method method = clazz.getMethod(methodName, paramTypes);
            //
            Object invoke = method.invoke(clazz.newInstance(), params);
            // 写回
            ctx.writeAndFlush(invoke);
        }
    }
}
